from PySide6.QtGui import QResizeEvent

from common import DocAndDocxThread
from ..base import WordFrameBase, ReturnView
from qfluentwidgets import StateToolTip, InfoBar


class DocAndDocxFrame(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.returnButton.clicked.connect(self.return_event)

        self.docToDocx = WordFrameBase()
        self.docToDocx.setTitle('Doc转Docx')
        self.docToDocx.setLabelText('Doc文件夹路径：', 'Docx文件夹路径：')
        self.docToDocx.started.connect(self.docToDocxThread)

        self.docxToDoc = WordFrameBase()
        self.docxToDoc.setTitle('Docx转Doc')
        self.docxToDoc.setLabelText('Docx文件夹路径：', 'Doc文件夹路径：')
        self.docxToDoc.started.connect(self.docxToDocThread)

        self.vBox.addWidget(self.returnButton)
        self.vBox.addWidget(self.docToDocx)
        self.vBox.addWidget(self.docxToDoc)

        self.stateToolTip = StateToolTip('', '', self)
        self.stateToolTip.hide()
        self.doc_thread = DocAndDocxThread(self)

        def started_thread():
            self.stateToolTip.show()
            self.docToDocx.startButton.setEnabled(False)
            self.docxToDoc.startButton.setEnabled(False)

        def finished_thread():
            self.stateToolTip.hide()
            self.docToDocx.startButton.setEnabled(True)
            self.docxToDoc.startButton.setEnabled(True)
            InfoBar.success('成功', '转换完成', parent=self)

        def error_thread(content):
            InfoBar.error('错误', content, parent=self)

        self.doc_thread.started.connect(started_thread)
        self.doc_thread.error.connect(error_thread)
        self.doc_thread.finished.connect(finished_thread)

    def docxToDocThread(self):
        self.stateToolTip.setTitle('docx转doc')
        self.stateToolTip.setContent('正在docx转doc，请稍后...')
        openFile, saveFile = self.docxToDoc.lineEditText()
        if openFile is False:
            return
        self.doc_thread.set_value(openFile, saveFile, 'docx_to_doc')
        self.doc_thread.start()

    def docToDocxThread(self):
        self.stateToolTip.setTitle('doc转docx')
        self.stateToolTip.setContent('正在doc转docx，请稍后...')
        openFile, saveFile = self.docToDocx.lineEditText()
        if openFile is False:
            return
        self.doc_thread.set_value(openFile, saveFile, 'doc_to_docx')
        self.doc_thread.start()

    def resizeEvent(self, a0: QResizeEvent):
        self.stateToolTip.move(a0.size().width() - 10 - self.stateToolTip.width(), 20)
        super().resizeEvent(a0)

    def return_event(self):
        self.docToDocx.clear()
        self.docxToDoc.clear()
        self.returned.emit()
